﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyHocPhi.BLL;
using QuanLyHocPhi.Model;
using System.IO;
using System.Diagnostics;
using QuanLyHocPhi.GUI.DuLieu;

namespace QuanLyHocPhi.GUI.TacNghiep
{
    public partial class FormThuLeHocPhiCaNhan : Form
    {
        bool lockUpdate = false;
        public SinhVien selectedSinhVien { get; set; }
        bool LaHocPhi = true;
        string fileName = "";
        string fileLuu = string.Format("{0}\\Documents\\TEMPLATES\\PhieuThu.xml",
               Application.StartupPath);
        string fileIn = string.Format("{0}\\Documents\\TEMPLATES\\PhieuThu.doc",
               Application.StartupPath);
        public FormThuLeHocPhiCaNhan(bool laHocPhi = true)
        {
            InitializeComponent();
            this.LaHocPhi = laHocPhi;
            if (LaHocPhi)
            {
                lbLeHocPhi.Text = "Học phí";
                lblHLPDaMienGiam.Text = "Học phí sau khi miễn giảm";
                this.Text = lbTieuDe.Text = "Thu học phí theo cá nhân";
                fileName = string.Format("{0}\\Documents\\TEMPLATES\\MauThuHocPhi.xml",
               Application.StartupPath);

            }
            else
            {
                lbLeHocPhi.Text = "Lệ phí";
                lblHLPDaMienGiam.Text = "Lệ phí sau khi miễn giảm";
                this.Text = lbTieuDe.Text = "Thu lệ phí theo cá nhân";
                fileName = string.Format("{0}\\Documents\\TEMPLATES\\MauThuLePhi.xml",
               Application.StartupPath);
            }



            #region Cấu hình lưới lịch sử nộp
            colNgayThu.DataPropertyName = "NgayThuStr";
            colNoiDungThu.DataPropertyName = "NoiDungThu";
            colSoPhieu.DataPropertyName = "SoPhieuNew";
            colSoQuyen.DataPropertyName = "SoQuyen";
            colSoTienDaNop.DataPropertyName = "SoTienStr";
            gridLichSuNop.AutoGenerateColumns = false;
            gridLichSuNop.AllowDrop = false;
            gridLichSuNop.AllowUserToAddRows = false;
            gridLichSuNop.AllowUserToDeleteRows = false;
            #endregion

            #region Cấu hình lưới danh sách sinh viên
            gridDSSinhVien.AllowDrop = false;
            gridDSSinhVien.AllowUserToAddRows = false;
            gridDSSinhVien.AllowUserToDeleteRows = false;
            gridDSSinhVien.AutoGenerateColumns = false;
            gridDSSinhVien.ShowFindBar = false;
            colMaSV.DataPropertyName = "MaSinhVien";
            colHoDem.DataPropertyName = "HoDem";
            colTen.DataPropertyName = "Ten";
            #endregion

            LoadNamHoc();
            LoadDien();
            LoadDoiTuong();
            LoadLoaiHinh();

        }

        private void LoadDien()
        {
            lockUpdate = true;
            var ds = BizLoaiHinhDaoTao.GetList_Dien();
            ds.Insert(0, "Tất cả");
            InitComboSuggestion(cmbDien, ds, null, null, ds.ToArray());
            //cmbNamHoc.ValueMember = "TenNamHoc";
            //cmbNamHoc.DisplayMember = "TenNamHoc";
            //cmbNamHoc.DataSource = ds;
            lockUpdate = false;
        }

        private void LoadDoiTuong()
        {
            lockUpdate = true;
            var ds = BizLoaiHinhDaoTao.GetList_DoiTuong();
            ds.Insert(0, "Tất cả");
            InitComboSuggestion(cmbDoiTuong, ds, null, null, ds.ToArray());
            //cmbNamHoc.ValueMember = "TenNamHoc";
            //cmbNamHoc.DisplayMember = "TenNamHoc";
            //cmbNamHoc.DataSource = ds;
            lockUpdate = false;
        }

        private void LoadCauHinhPhieuThu()
        {
            List<int> cauHinhPhieuThu = null;
            if (LaHocPhi)
                cauHinhPhieuThu = BizCauHinh.GetCauHinh();
            else
                cauHinhPhieuThu = BizCauHinh.GetCauHinh(false);

            if (cauHinhPhieuThu != null && cauHinhPhieuThu.Count == 2)
            {
                txtQuyenSo.Text = cauHinhPhieuThu[0].ToString();
                txtSoPhieu.Text = cauHinhPhieuThu[1].ToString();
            }
            else
            {
                txtQuyenSo.Text = "1";
                txtSoPhieu.Text = "1";
            }
        }

        private void LoadNamHoc()
        {
            lockUpdate = true;
            var ds = BizNamHoc.GetListNamHoc();
            InitComboSuggestion(cmbNamHoc, ds, "TenNamHoc", "TenNamHoc", ds.Select(e => e.TenNamHoc).ToArray());
            //cmbNamHoc.ValueMember = "TenNamHoc";
            //cmbNamHoc.DisplayMember = "TenNamHoc";
            //cmbNamHoc.DataSource = ds;
            lockUpdate = false;
            LoadHocKy();
        }

        private void LoadHocKy()
        {
            lockUpdate = true;
            cmbHocKy.DataSource = null;
            if ((cmbNamHoc.SelectedItem as NamHoc) != null)
            {
                var ds = BizHocKy.GetList_HocKy((cmbNamHoc.SelectedItem as NamHoc).TenNamHoc);
                //InitComboSuggestion(cmbHocKy, ds, "TenHocKy", "MaHocKy", ds.Select(e => e.TenHocKy.ToString()).ToArray());
                cmbHocKy.DataSource = ds;
                cmbHocKy.DisplayMember = "TenHocKy";
                cmbHocKy.ValueMember = "MaHocKy";
                if (ds != null && ds.Count > 0)
                {
                    if (bdsDsSinhVien.DataSource != null)
                    {
                        bntNhap.Enabled = true;
                        bntNhapVaIn.Enabled = true;
                    }
                }
                else
                {
                    bntNhap.Enabled = false;
                    bntNhapVaIn.Enabled = false;
                }
                lockUpdate = false;
                //LoadLichSuNopHP();
                LoadLeHocPhi();
                LoadNoiDungHocPhi();

            }
        }

        private void LoadNoiDungHocPhi()
        {
            txtNoiDungThu.Text = "";
            if (cmbNamHoc.SelectedIndex != -1 && cmbHocKy.SelectedIndex != -1)
            {
                var hk = cmbHocKy.SelectedItem as HocKy;
                var nh = cmbNamHoc.SelectedItem as NamHoc;
                txtNoiDungThu.Text = string.Format("{2} học kỳ {0} năm học {1}", hk.TenHocKy, nh.TenNamHoc, LaHocPhi ? "Học phí" : "Lệ phí");
            }
        }

        private void LoadTongTienTheoLop()
        {
            LopGoc lopGoc = null;
            if (cmbLop.SelectedItem != null)
                lopGoc = cmbLop.SelectedItem as LopGoc;
            if (lopGoc == null)
                return;
            HocKy hocKy = null;
            if (cmbHocKy.SelectedItem != null)
                hocKy = cmbHocKy.SelectedItem as HocKy;
            if (hocKy == null)
                return;
            long tongTienDaNop = 0;
            long tongLeHocPhi = 0;
            BizSinhVien.GetTongTien(lopGoc.MaLopGoc, cmbNamHoc.SelectedValue.ToString(), ref tongLeHocPhi, ref tongTienDaNop, LaHocPhi);
            lbSoTienLopNop.Text = tongTienDaNop.ToString().FormatCurrency() + "/" + tongLeHocPhi.ToString().FormatCurrency() + " đồng";
        }

        private void LoadLeHocPhi()
        {
            LoadLichSuNopHP();
            errorProvider1.Clear();
            if (cmbHocKy.SelectedIndex != -1 && bdsDsSinhVien.Current != null)
            {
                if (selectedSinhVien != null)
                {
                    //var lhp = BizPhiMacDinh.GetLeHocPhi(selectedSinhVien.MaLopGoc, (cmbHocKy.SelectedItem as HocKy).MaHocKy, LaHocPhi);
                    var sinhVien = bdsDsSinhVien.Current as SinhVien;
                    var hocKy = cmbHocKy.SelectedItem as HocKy;
                    if (sinhVien == null || hocKy == null)
                        return;
                    var lhp = BizBienCheSinhVienVaoHocKy.GetBienCheSinhVienTheoHocKy(sinhVien.MaSinhVien, hocKy.MaHocKy);
                    if (lhp == null)
                    {
                        txtHocPhi.Text = "";
                        txtMienGiam.Text = "";
                        txtHocPhiSauKhiMienGiam.Text = "";
                        txtSoTienNop.Text = "";
                        return;
                    }
                    var mienGiam = decimal.Parse(txtMienGiam.Text);
                    if (LaHocPhi)
                    {
                        txtHocPhi.Text = lhp.HocPhi.ToString();
                        try
                        {
                            long hpSMG = (long)(lhp.HocPhi - lhp.HocPhi * mienGiam);
                            txtHocPhiSauKhiMienGiam.Text = hpSMG.ToString();
                            long tongTienDaNop = 0;
                            if (hocKy.TenHocKy == 1)
                            {
                                var lsPhieuThu = BizPhieuThu.GetLichSuNopLePhi1HocKy(sinhVien.MaSinhVien, hocKy.MaHocKy, ref tongTienDaNop, LaHocPhi);
                                txtSoTienNop.Text = (tongTienDaNop >= hpSMG) ? "0" : (hpSMG - tongTienDaNop).ToString();
                            }
                        }
                        catch
                        {
                            txtSoTienNop.Text = lhp.ToString();
                            errorProvider1.SetError(txtMienGiam, "Vui lòng nhập hệ số miễn giảm từ 0 -> 1");
                        }
                    }
                    else
                    {
                        txtHocPhi.Text = lhp.LePhi.ToString();
                        try
                        {
                            long hpSMG = (long)(lhp.LePhi - lhp.LePhi * mienGiam);
                            txtHocPhiSauKhiMienGiam.Text = hpSMG.ToString();
                            long tongTienDaNop = 0;
                            if (hocKy.TenHocKy == 1)
                            {
                                var lsPhieuThu = BizPhieuThu.GetLichSuNopLePhi1HocKy(sinhVien.MaSinhVien, hocKy.MaHocKy, ref tongTienDaNop, LaHocPhi);
                                txtSoTienNop.Text = (tongTienDaNop >= hpSMG) ? "0" : (hpSMG - tongTienDaNop).ToString();
                            }
                        }
                        catch
                        {
                            txtSoTienNop.Text = lhp.ToString();
                            errorProvider1.SetError(txtMienGiam, "Vui lòng nhập hệ số miễn giảm từ 0 -> 1");
                        }
                    }
                }
            }
            else
            {
                txtMienGiam.Text = "";
                txtHocPhi.Text = "";
                txtSoTienNop.Text = "";
            }
            //txtSoTienNop.Focus();
        }

        /// <summary>
        /// Tải lịch sử nộp học phí trên 1 học kỳ của sinh viên
        /// </summary>
        private void LoadLichSuNopHP()
        {
            bdsLichSuNop.DataSource = null;
            gridLichSuNop.DataSource = bdsLichSuNop;
            long tongTienDaNop = 0;
            lbTongTienDaNop.Text = "0 đồng";
            if (bdsDsSinhVien.Current != null && cmbNamHoc.SelectedIndex != -1)
            {
                var sinhVien = bdsDsSinhVien.Current as CustomSinhVien;
                if (sinhVien == null)
                    return;
                var msv = sinhVien.MaSinhVien;
                var tenNamHoc = (cmbNamHoc.SelectedItem as NamHoc).TenNamHoc;
                var ds = BizPhieuThu.GetLichSuNopLePhiCaNam(msv, tenNamHoc, ref tongTienDaNop, LaHocPhi);
                bdsLichSuNop.DataSource = ds;
                gridLichSuNop.DataSource = bdsLichSuNop;
                HocKy hocKy = null;
                if (cmbHocKy.SelectedIndex != -1)
                    hocKy = cmbHocKy.SelectedItem as HocKy;
                var lsBC = BizBienCheSinhVienVaoHocKy.GetBienCheSinhVien(msv, tenNamHoc);
                if (lsBC != null && lsBC.Count > 0)
                {
                    if (ds != null && ds.Count > 0)
                        txtMienGiam.Text = lsBC[0].Giam.ToString();
                    else
                        txtMienGiam.Text = sinhVien.Giam.HasValue ? sinhVien.Giam.ToString() : "0";
                    decimal soTienPhaiNop = 0;
                    if (LaHocPhi)
                        soTienPhaiNop = lsBC.Sum(t => t.HocPhi - t.HocPhi * t.Giam);
                    else
                        soTienPhaiNop = lsBC.Sum(t => t.LePhi - t.LePhi * t.Giam);
                    lbTongTienDaNop.Text = tongTienDaNop.ToString().FormatCurrency() + "/" + soTienPhaiNop.ToString().FormatCurrency() + " đồng";
                    if (hocKy.TenHocKy == 2)
                    {
                        //var lsPhieuThu = BizPhieuThu.GetLichSuNopLePhi1HocKy(sinhVien.MaSinhVien, hocKy.MaHocKy, ref tongTienDaNop, LaHocPhi);
                        txtSoTienNop.Text = (tongTienDaNop >= soTienPhaiNop) ? "0" : (soTienPhaiNop - tongTienDaNop).ToString().FormatCurrency();
                    }
                }
                else
                {
                    lbTongTienDaNop.Text = "0/0 đồng";
                    txtSoTienNop.Text = "0";
                }
            }

        }

        private void cmbNamHoc_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadHocKy();
                LoadTongTienTheoLop();
            }
        }

        private void cmbHocKy_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                //LoadLichSuNopHP();
                LoadLeHocPhi();
                LoadNoiDungHocPhi();
            }
        }

        private void bntNhap_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtHocPhi.Text))
                DialogUtils.ShowError("Bạn chưa nhập học phí cho sinh viên này");
            else
                NhapPhieuThuVaoCSDL();
        }

        private void bntNhapVaIn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtHocPhi.Text))
                DialogUtils.ShowError("Bạn chưa nhập học phí cho sinh viên này");
            else
                NhapPhieuThuVaoCSDL(true);
        }

        /// <summary>
        /// Nhập phiếu thu
        /// </summary>
        /// <param name="inPhieuThu">True: In phiếu; False: không in phiếu</param>
        void NhapPhieuThuVaoCSDL(bool inPhieuThu = false)
        {
            errorProvider1.Clear();

            #region Lấy thông tin học kỳ
            if (cmbHocKy.SelectedIndex == -1)
                return;
            var hocKy = cmbHocKy.SelectedItem as HocKy;
            #endregion

            #region Lấy thông tin học phí
            int sHocPhi = 0;
            int temp = 0;
            var soTien = txtHocPhi.Text.Replace(".", "").Replace(",", "");
            if (int.TryParse(soTien, out temp))
                sHocPhi = int.Parse(soTien);
            else
            {
                DialogUtils.ShowError("Nhập sai học phí");
                return;
            }
            int sSoTienNop = 0;
            soTien = txtSoTienNop.Text.Replace(".", "").Replace(",", "");
            if (int.TryParse(soTien, out temp))
                sSoTienNop = int.Parse(soTien);
            else
            {
                DialogUtils.ShowError("Nhập sai số tiền cần nộp");
                return;
            }
            #endregion

            #region Lấy thông tin về số biên lai

            var quyenSo = 1;
            var soPhieu = 1;
            int temp2 = 0;
            if (int.TryParse(txtQuyenSo.Text, out temp2))
            {
                quyenSo = int.Parse(txtQuyenSo.Text);
            }
            else
            {
                errorProvider1.SetError(txtQuyenSo, "Quyển số không hợp lệ");
                return;
            }

            if (int.TryParse(txtSoPhieu.Text, out temp2))
            {
                soPhieu = int.Parse(txtSoPhieu.Text);
            }
            else
            {
                errorProvider1.SetError(txtQuyenSo, "Số phiếu không hợp lệ");
                return;
            }

            decimal tt = 0;
            if (!decimal.TryParse(txtMienGiam.Text, out tt))
            {
                errorProvider1.SetError(txtMienGiam, "Miễn giảm không đúng");
                return;
            }
            #endregion

            //Biên chế sinh viên vào một một học kỳ
            var bienChe = BizBienCheSinhVienVaoHocKy.BienCheSinhVien(selectedSinhVien.MaSinhVien, hocKy.MaHocKy, sHocPhi, decimal.Parse(txtMienGiam.Text), LaHocPhi);
            //Tạo mới một phiếu thu
            var phieuThu = new PhieuThu()
            {
                MaPhieuThu = Guid.NewGuid().ToString(),
                SoQuyen = quyenSo.ToString(),
                SoPhieu = soPhieu.ToString(),
                NoiDungThu = txtNoiDungThu.Text,
                NgayThu = dateNgayNop.Value.Date,
                MaBienChe = bienChe.MaBienChe,
                MaNguoiThu = Program.NguoiSuDung.TenDangNhap,
                SoTien = sSoTienNop,
                DaIn = false,
                HinhThucNop = rbTienMat.Checked ? 0 : 1,
            };
            phieuThu.LaHocPhi = LaHocPhi;

            #region Tạo mới phiếu thu, cập nhật số biên lai và in phiếu thu
            if (BizPhieuThu.CreatePhieuThu(phieuThu))
            {
                if (inPhieuThu)
                {
                    InPhieuThu(phieuThu);
                }
            }
            //Tăng số phiếu và số quyển
            BizCauHinh.IncrementCauHinh(ref quyenSo, ref soPhieu);
            //Cập nhật lại số biên lai
            BizCauHinh.UpdateCauHinh(quyenSo.ToString(), soPhieu.ToString(), LaHocPhi);
            #endregion

            DialogUtils.ShowMessage("Đã lập phiếu thu " + (LaHocPhi ? "học phí" : "lệ phí") + " cho sinh viên " + selectedSinhVien.HoDem + " " + selectedSinhVien.Ten + " thành công");
            LoadLichSuNopHP();
        }

        /// <summary>
        /// In phiếu thu
        /// </summary>
        /// <param name="phieuThu"></param>
        private void InPhieuThu(PhieuThu phieuThu)
        {
            try
            {
                if (!File.Exists(fileName))
                {
                    DialogUtils.ShowMessage("File mẫu phiếu thu không tồn tại. Xin vui lòng kiểm tra lại hoặc liên hệ với người quản trị");
                    return;
                }
                if (File.Exists(fileLuu))
                    File.Delete(fileLuu);
                if (File.Exists(fileIn))
                    File.Delete(fileIn);
                var pt = BizPhieuThu.GetPhieuThuFull(phieuThu.MaPhieuThu);

                String fileContents = System.IO.File.ReadAllText(fileName);
                fileContents = fileContents.Replace("{ngay}", pt.NgayThu.Day.ToString());
                fileContents = fileContents.Replace("{thang}", pt.NgayThu.Month.ToString());
                fileContents = fileContents.Replace("{nam}", pt.NgayThu.Year.ToString());
                fileContents = fileContents.Replace("{quyenSo}", pt.SoQuyen);
                fileContents = fileContents.Replace("{soPhieu}", pt.SoPhieu);
                fileContents = fileContents.Replace("{tenSinhVien}", pt.BienCheSinhVienVaoHocKy.SinhVien.HoDem + " " + pt.BienCheSinhVienVaoHocKy.SinhVien.Ten);
                fileContents = fileContents.Replace("{diaChi}", pt.BienCheSinhVienVaoHocKy.SinhVien.LopGoc.TenLopGoc);
                fileContents = fileContents.Replace("{noiDung}", pt.NoiDungThu);
                fileContents = fileContents.Replace("{soTien}", pt.SoTien.ToString().FormatCurrency());
                fileContents = fileContents.Replace("{soTienBangChu}", pt.SoTien.ToString().ConvertNum2Text());
                fileContents = fileContents.Replace("{nguoiThu}", pt.NguoiSuDung.HoTen);
                fileContents = fileContents.Replace("{banSao}", "");
                System.IO.File.WriteAllText(fileLuu, fileContents);
                File.Move(fileLuu, fileIn);
                ProcessStartInfo info = new ProcessStartInfo(fileIn);
                info.Verb = "Print";
                info.CreateNoWindow = true;
                info.WindowStyle = ProcessWindowStyle.Hidden;
                Process.Start(info);
                phieuThu.DaIn = true;
                BizPhieuThu.Update(phieuThu);
            }
            catch (Exception ex)
            {
                DialogUtils.ShowError("Lỗi: " + ex.ToString());
            }
        }

        private void bdsLichSuNop_DataSourceChanged(object sender, EventArgs e)
        {

        }

        private void gridLichSuNop_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void LoadLoaiHinh()
        {
            lockUpdate = true;
            var ds = BizLoaiHinhDaoTao.GetListLoaiHinh();
            LoaiHinhDaoTao loaiHinh = new LoaiHinhDaoTao
            {
                MaLoaiHinh = "-1",
                TenLoaiHinh = "Tất cả"

            };
            ds.Insert(0, loaiHinh);
            InitComboSuggestion(cmbLoaiHinh, ds, "TenLoaiHinh", "MaLoaiHinh", ds.Select(e => e.TenLoaiHinh).ToArray());
            //cmbLoaiHinh.DataSource = ds;
            //cmbLoaiHinh.DisplayMember = "TenLoaiHinh";
            //cmbLoaiHinh.ValueMember = "MaLoaiHinh";
            lockUpdate = false;
            LoadNamTuyenSinh();
        }

        private void InitComboSuggestion(ComboBox cmb, object datasource, string displayMember, string valueMember, string[] rangeDisplay)
        {
            cmb.AutoCompleteSource = AutoCompleteSource.CustomSource;
            cmb.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cmb.DataSource = datasource;
            if (displayMember != null)
                cmb.DisplayMember = displayMember;
            if (valueMember != null)
                cmb.ValueMember = valueMember;
            // Xác định AutoCompleteCustomeSource
            var autoCompletSet = new AutoCompleteStringCollection();
            autoCompletSet.AddRange(rangeDisplay);
            cmb.AutoCompleteCustomSource = autoCompletSet;

            // Các tinh chỉnh nâng cao
            cmb.Leave += (oSender, oE) =>
            {
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };

            cmb.KeyDown += (oSender, oE) =>
            {
                if (oE.KeyCode != Keys.Enter)
                    return;
                var cbx = oSender as ComboBox;
                if (cbx == null)
                    return;
                cbx.BackColor = cbx.SelectedItem == null ? Color.LightPink : SystemColors.Window;
            };
        }

        private void LoadNamTuyenSinh()
        {
            if (cmbLoaiHinh.SelectedIndex != -1)
            {
                lockUpdate = true;
                cmbNamTuyenSinh.DataSource = null;
                IList<string> ds = new List<string>();
                if (cmbLoaiHinh.SelectedIndex != 0)
                {
                    ds = BizLoaiHinhDaoTao.GetList_NamTuyenSinh((cmbLoaiHinh.SelectedItem as LoaiHinhDaoTao).MaLoaiHinh);
                }
                ds.Insert(0, "Tất cả");
                InitComboSuggestion(cmbNamTuyenSinh, ds, null, null, ds.ToArray());
                //cmbNamTuyenSinh.DataSource = ds;
                lockUpdate = false;
                LoadLopGoc();
            }
        }

        private void LoadLopGoc()
        {
            lockUpdate = true;
            cmbLop.DataSource = null;
            bool dontLoadDs = cmbNamTuyenSinh.SelectedIndex == -1 || cmbLoaiHinh.SelectedIndex == -1;
            if (dontLoadDs)
                return;
            var maLoaiHinh = cmbLoaiHinh.SelectedValue.ToString();
            var namTs = cmbNamTuyenSinh.SelectedValue.ToString();
            if (namTs == "Tất cả")
                namTs = "-1";
            var ds = new List<LopGoc>();

            if (!dontLoadDs)
                ds = BizLopGoc.GetListLopGoc(maLoaiHinh, namTs);


            var lopGoc = new LopGoc
            {
                MaLopGoc = "-1",
                TenLopGoc = "Tất cả"
            };
            ds.Insert(0, lopGoc);
            InitComboSuggestion(cmbLop, ds, "TenLopGoc", "MaLopGoc", ds.Select(e => e.TenLopGoc).ToArray());
            //cmbLop.DataSource = ds;
            //cmbLop.DisplayMember = "TenLopGoc";
            //cmbLop.ValueMember = "MaLopGoc";
            lockUpdate = false;
            cmbLop_SelectedIndexChanged(this, new EventArgs());


        }

        private void cmbLop_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void LoadDanhSachSinhVien()
        {
            lockUpdate = true;
            bdsDsSinhVien.DataSource = null;
            gridDSSinhVien.DataSource = bdsDsSinhVien;
            if (cmbLop.SelectedIndex != -1)
            {
                LopGoc lopGoc = null;
                if (cmbLop.SelectedItem != null)
                    lopGoc = cmbLop.SelectedItem as LopGoc;
                if (lopGoc == null)
                    return;
                HocKy hocKy = null;
                if (cmbHocKy.SelectedItem != null)
                    hocKy = cmbHocKy.SelectedItem as HocKy;
                if (hocKy == null)
                    return;
                var maLoaiHinh = cmbLoaiHinh.SelectedValue.ToString();
                var namTS = cmbNamTuyenSinh.SelectedValue.ToString();
                if (namTS == "Tất cả")
                    namTS = "-1";
                var dien = cmbDien.SelectedValue.ToString();
                if (dien == "Tất cả")
                    dien = "-1";
                var doiTuong = cmbDoiTuong.SelectedValue.ToString();
                if (doiTuong == "Tất cả")
                    doiTuong = "-1";
                decimal tongTienDaNop = 0;
                decimal tongLeHocPhi = 0;
                var namHoc = cmbNamHoc.SelectedValue.ToString();
                //var keyWord = txtKeyword.Text.Trim();
                var ds = new List<CustomSinhVien>();
                FormProgress frm = new FormProgress();
                frm.DoWork += delegate(object oSender, DoWorkEventArgs oE)
                {
                    ds = BizSinhVien.GetDanhSachSinhVien(
                        maLoaiHinh,
                        namTS,
                        lopGoc.MaLopGoc,
                        doiTuong,
                        dien,
                      namHoc,
                        ref tongLeHocPhi,
                        ref tongTienDaNop,
                        LaHocPhi,
                        null);
                };
                frm.RunWorkerCompleted += delegate(object oSender, RunWorkerCompletedEventArgs oE)
                {
                    if (oE.Error != null)
                    {
                        string msg = oE.Error.Message;
                        if (oE.Error.InnerException != null)
                            msg += oE.Error.InnerException.Message;
                        DialogUtils.ShowError(msg);
                    }
                    lbSoTienLopNop.Text = tongTienDaNop.ToString().FormatCurrency() + "/" + tongLeHocPhi.ToString().FormatCurrency() + " đồng";
                    bdsDsSinhVien.DataSource = ds;
                    gridDSSinhVien.DataSource = bdsDsSinhVien;
                    lockUpdate = false;
                };
                frm.StartWorking(this);
            }
        }

        private void cmbLoaiHinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadNamTuyenSinh();
            }
        }

        private void cmbNamTuyenSinh_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!lockUpdate)
            {
                LoadLopGoc();
            }
        }

        private void bdsDsSinhVien_CurrentChanged(object sender, EventArgs e)
        {
            LoadThongTinSinhVien();
            LoadLeHocPhi();
            //LoadLichSuNopHP();
            LoadCauHinhPhieuThu();
        }

        private void LoadThongTinSinhVien()
        {
            txtLopNamTS.Text = "";
            if (bdsDsSinhVien.DataSource != null && (bdsDsSinhVien.Current as SinhVien) != null)
            {
                selectedSinhVien = bdsDsSinhVien.Current as SinhVien;
                if (selectedSinhVien != null)
                {
                    selectedSinhVien = BizSinhVien.GetSinhVienByMSV(selectedSinhVien.MaSinhVien);
                    txtMaSinhVien.Text = selectedSinhVien.MaSinhVien;
                    txtHoTen.Text = selectedSinhVien.HoDem + " " + selectedSinhVien.Ten;
                    txtNgaySinh.Text = selectedSinhVien.NgaySinh;
                    var lop = BizLopGoc.GetLopGoc(selectedSinhVien.MaLopGoc);
                    if (lop != null)
                        txtLopNamTS.Text = string.Format("{0} - {1}", lop.TenLopGoc, lop.NamTuyenSinh);
                    //txtMienGiam.Text = selectedSinhVien.Giam.HasValue ? selectedSinhVien.Giam.ToString() : "0";
                }
            }
            else
            {
                selectedSinhVien = null;
                txtMaSinhVien.Text = "";
                txtHoTen.Text = "";
                txtNgaySinh.Text = "";
                //txtMienGiam.Text = "0";
            }
        }

        private void bdsDsSinhVien_DataSourceChanged(object sender, EventArgs e)
        {
            if (bdsDsSinhVien.DataSource != null && cmbHocKy.DataSource != null)
            {
                bntNhap.Enabled = true;
                bntNhapVaIn.Enabled = true;
            }
            else
            {
                bntNhap.Enabled = false;
                bntNhapVaIn.Enabled = false;
            }
            //lblDanhSachSinhVien_ThongKe.Text = string.Format("{0} sinh viên", bdsDsSinhVien.Count);
        }

        private void cmbHocKy_DataSourceChanged(object sender, EventArgs e)
        {
            if (bdsDsSinhVien.DataSource != null && cmbHocKy.DataSource != null)
            {
                bntNhap.Enabled = true;
                bntNhapVaIn.Enabled = true;
            }
            else
            {
                bntNhap.Enabled = false;
                bntNhapVaIn.Enabled = false;
            }
        }

        private void txtKeyword_TextChanged(object sender, EventArgs e)
        {
            LoadDanhSachSinhVien();
        }

        private void txtSoTienNop_TextChanged(object sender, EventArgs e)
        {
            int temp = 0;
            var soTienNop = txtSoTienNop.Text.Replace(".", "").Replace(",", "");
            if (int.TryParse(soTienNop, out temp))
            {

                lbTienBangChu.Text = int.Parse(soTienNop).ToString().ConvertNum2Text();
                txtSoTienNop.Text = soTienNop.FormatCurrency();
                txtSoTienNop.Select(txtSoTienNop.Text.Length, 0);
            }
        }

        private void txtHocPhi_TextChanged(object sender, EventArgs e)
        {
            int temp = 0;
            var hocPhi = txtHocPhi.Text.Replace(".", "").Replace(",", "");
            if (int.TryParse(hocPhi, out temp))
            {
                txtHocPhi.Text = hocPhi.FormatCurrency();
                txtHocPhi.Select(txtHocPhi.Text.Length, 0);
            }
        }

        private void txtMienGiam_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtSoPhieu_TextChanged(object sender, EventArgs e)
        {
            int temp = 0;
            if (int.TryParse(txtSoPhieu.Text, out temp))
            {
                int soPhieu = int.Parse(txtSoPhieu.Text);
                txtQuyenSo.Text = (soPhieu / 50 + (soPhieu % 50 == 0 ? 0 : 1)).ToString();
            }
        }

        private void txtHocPhiSauKhiMienGiam_TextChanged(object sender, EventArgs e)
        {
            int temp = 0;
            var hocPhi = txtHocPhiSauKhiMienGiam.Text.Replace(".", "").Replace(",", "");
            if (int.TryParse(hocPhi, out temp))
            {
                txtHocPhiSauKhiMienGiam.Text = hocPhi.FormatCurrency();
                txtHocPhiSauKhiMienGiam.Select(txtHocPhiSauKhiMienGiam.Text.Length, 0);
            }
        }

        private void txtMienGiam_Leave(object sender, EventArgs e)
        {
            float temp = 0;
            if (float.TryParse(txtMienGiam.Text, out temp))
                ;//LoadLeHocPhi();
            else
                txtMienGiam.Focus();
        }

        private void btnLoc_Click(object sender, EventArgs e)
        {
            LoadDanhSachSinhVien();
            //LoadTongTienTheoLop();
            //LoadLichSuNopHP();
            LoadLeHocPhi();
        }
    }
}
